<?php
declare (strict_types=1);

namespace app\api\controller;


use addons\WeChatMini\facade\WeChatMini;
use app\common\model\User;
use app\common\model\User as UserModel;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\Response;
use WeMini\Crypt;

class Login extends Base
{

    /**
     * 原点 2022年2月16日14:16:31 小程序授权登录
     */
    public function miniAppletLogin(): Response
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'MiniAppletLogin');
            $result = (new Crypt(config('pay')['wechat']))->session($param['code']);

            $result['nickname'] = $param['nickname'];
            $result['photo'] = $param['photo'];
            return json(User::_miniAppletSave($result));

        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * post: 登录注册
     * path: login
     * method: login
     * param: code - {string} code
     */
    public function login(): Response
    {
        //首先 use app\common\facade\WeChat;
        try {

            $post = $this->request->post();
            $getPhoneNumber = WeChatMini::getPhoneNumber($post['mobile']);
//            dump($getPhoneNumber);die;
//            $result = WeChatMini::session($post['code']);
            $result = WeChatMini::getUserInfo($post['code'], $post['iv'],  $post['encryptedData']);

//            var_dump($getPhoneNumber);die;
//            $where['openid'] = $result['openid'];
            $where['mobile'] = $getPhoneNumber['phone_info']['phoneNumber'];
            $user = User::where($where)->find();
            if($user)
            {
                $time = time();
                $token = md5(json_encode($user) . $time . $this->request->ip());
                $user->token = $token;
                if(!$user->openid)
                {
                    $user->openid = $result['openid'];
                }
                $user->last_time = $time;
                $user->last_ip = $this->request->ip();
                $user->save();
            }else{
                $param['code'] = generate(6, '', 1);
                $param['openid'] = $result['openid'];
                $param['nickname'] = $result['nickName'];
                $param['last_time'] = time();
                $param['last_ip'] = $this->request->ip();
                $token = md5(json_encode($user) . time() . $this->request->ip());
                $param['token'] = $token;
                $param['mobile'] = $getPhoneNumber['phone_info']['phoneNumber'];
                $param['name'] = substr($param['mobile'],-4);
                $param['pay_password'] = md5('222222');
//                if(isset($post['parent_code']))
//                {
//                    $parent = User::where(['code' => $post['parent_code'], 'is_del' => 0])->find();
//                    if (empty($parent)) {
//                        return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
//                    }
//                    $param['parent_code'] = $post['parent_code'];
//                    $param['parent_id'] = $parent->id;
//                    $param['parent_name'] = $parent->nickname;
//                }

                User::create($param);
            }
            $data['token'] = $token;

            return Result::success('登录成功', $data);
//            var_dump($result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }


}
